<template>
  <div class="box">
    <img src="/public/shop.jpg" alt="" width="100%" height="99%" />
    <div class="box1">
      <p class="p1">社区团购</p>
      <p class="p2">A X L a b 社 区 团 管 理 中 心</p>
    </div>
    <div class="box2">
      <div class="box3">
        <h4>Axlab社区团购</h4>
        <p style="margin-top: 10px; color: #999999; font-size: 14px">
          系统管理账号登录
        </p>
        <div class="box4">
          <el-input v-model="username" style="width: 100%; height: 45px" placeholder="请输入用户名" :prefix-icon="User" />
          <el-input v-model="password" style="width: 100%; height: 45px" placeholder="请输入密码" :prefix-icon="Unlock" type="password" show-password/>
        </div>
        <p style="margin: 20px 0">
          
          <span style="
              position: fixed;
              top: -300;
              font-size: 14px;
              color: #999999;
            " @click="show = true; startCamera();">人脸识别登录?</span>
          <span style="
              float: right;
              color: #409eff;
              font-size: 14px;
              color: rgb(216, 213, 213);
            "
            @click="router.push('/Account')"
            >忘记密码?</span>
        </p>
        <p style="margin-top: 55px;">
          <span style="font-size: 15px;">还没有账号?</span>  <span style="font-size: 15px;color: rgb(216, 213, 213);" @click="Register">立即注册</span>
        </p>
        <van-button type="danger" block style="width: 100%; margin-top: 20px" @click="submit">立即登录</van-button>
      </div>
    </div>
    <van-overlay :show="show" >
      <h3 class="header-text">人脸登录验证</h3>
      <div class="face_container"   >
          <video ref="videoRef" class="video-element"></video>
      </div>
      <div class="face_container_1"  >
          <canvas ref="canvasRef" class="canvas-element"></canvas>
      </div>
      <div style="width:250px;margin-left: 700px;">
          <button @click="capture" style="width:100px;height:40px;background-color: rgb(36, 153, 248);color: white;border-radius: 5px;">登录</button>
      </div>
      <p v-if="flag" class="success-message">登录成功！正在跳转...</p>
      <p v-if="flag1" class="error-message">登录失败，请重试。</p> 
    </van-overlay>
  </div>
</template>

<script setup>
import { Unlock, User, ChatDotRound } from '@element-plus/icons-vue';
import { ElMessage } from "element-plus";
import axios from 'axios';
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
const show = ref(false)
const router = useRouter();
const back = () => {
  router.go(-1);
};
const username = ref('');
const password = ref('');
const Verification = ref('');
const show1 = ref(true)
const Register = ()=>{
  router.push('/Register')
}

const submit = async() => {
  if(username.value == '' && password.value == ''){
    alert('请输入账号密码')
  }else{
    const {data} = await axios.post('http://localhost:3000/jsb/getlogin', {
      username: username.value,
      password: password.value
    })
    if(data.code == 200){
      localStorage.setItem('token', data.token)
      localStorage.setItem('result', JSON.stringify(data.result))
      ElMessage({
        message: '登录成功',
        type: 'success',
      })
      router.push('/index')
    }else{
      ElMessage({
        message: '账号或密码错误',
        type: 'error',
      })
    }
  }
}

const flag = ref(false);
const flag1 = ref(false);
const videoRef = ref('');
const canvasRef = ref('');
let stream; // Declare stream variable to manage video feed
const onClickLeft = () => history.back();
// Start camera function
const startCamera = async () => {
  try {
      stream = await navigator.mediaDevices.getUserMedia({ video: true });
      if (videoRef.value) {
          videoRef.value.srcObject = stream;
          videoRef.value.play();
      }
  } catch (error) {
      console.error('访问摄像头出错：', error);
  }
};

// Close camera function
const closeMedia = () => {
  if (stream) {
   // 获取所有视频轨道并停止
   stream.getVideoTracks().forEach((track) => track.stop());
    // 清除视频流
    document.querySelector("video").srcObject = null;
  }
};

// Capture image function
const capture = () => {
  if (!canvasRef.value || !videoRef.value) return;
  const canvas = canvasRef.value;
  const context = canvas.getContext('2d');
  context.drawImage(videoRef.value, 0, 0, canvas.width, canvas.height);
  const imageSrc = canvas.toDataURL('image/jpeg');
  submitImages(imageSrc); // Directly submit the captured image
};

// Submit images function
const submitImages = async (img) => {
  try {
      const res = await axios.post('http://127.0.0.1:3000/jsb/faceLogin', { b64: img });
      console.log(res);
      handleResponse(res.data);
  } catch (error) {
      console.error('提交图像出错', error);
      flag1.value = true;
  }
};

// Handle server response
const handleResponse = (data) => {
  if (data.code === 200) {
    localStorage.setItem('token', data.token);
    localStorage.setItem('result', JSON.stringify(data.result))
      flag.value = true;
      setTimeout(() => {
          flag.value = false;
          router.push('/index'); // Assuming `navigate` is defined elsewhere
      }, 2000);
  } else if (data.code === 401) {
      flag1.value = true;
      setTimeout(() => {
          flag1.value = false;
      }, 2000);
  }
};


onBeforeUnmount(() => {
  closeMedia(); // Clean up camera resources on component unmount
});
</script>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
}

.box {
  width: 100vw;
  height: 100vh;

  img {
    filter: blur(5px);
    z-index: -1;
  }
}

.box1 {
  position: absolute;
  top: 120px;
  left: 50px;
  color: rgb(255, 255, 255);

  .p1 {
    font-size: 80px;
  }

  .p2 {
    margin-top: 10px;
    font-size: 25px;
    font-weight: 700;
  }
}

.box2 {
  width: 450px;
  height: 100%;
  background-color: rgb(255, 255, 255);
  position: absolute;
  top: 0;
  right: 0;
}

.box3 {
  width: 80%;
  height: 50%;
  margin: 150px auto;
}

.box4 {
  width: 100%;
  height: 120px;
  margin-top: 30px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.face_header {
  width: 100vw;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10px;
  box-sizing: border-box;
  border-bottom: 1px solid #f1f1f1;
}

.header-text {
  padding-left: 35px;
  margin-top: 10px;
  margin-bottom: -15px;
}

.face_container {
  border: 1px solid black;
  width: 10vw;
  height: 10vw;
  overflow: hidden;
  position: relative;
  border-radius: 50%;
  margin: 50px auto;

}
.face_container_1 {
  width: 10vw;
  height: 10vw;
  overflow: hidden;
  position: relative;
  border-radius: 50%;
  margin: 50px auto;

}

.video-element {
  width: 150%;
  height: 100%;
  position: absolute;
  top: 0%;
  left: -45px;

}

.canvas-element {
  width: 150%;
  height: 100%;
  position: absolute;
  top: 0%;
  left: -45px;
}

.success-message {
  color: green;
  padding-left: 35px;
}
</style>